package com.ktgj.customer.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.ktgj.common.core.text.UUID;
import com.ktgj.common.core.utils.HttpClientUtil;
import com.ktgj.common.core.utils.RSAUtils;
import com.ktgj.common.core.utils.StringUtils;
import com.ktgj.common.core.utils.xml.XElement;
import com.ktgj.customer.domain.BillPayment;
import com.ktgj.customer.domain.Insurance.*;
import com.ktgj.customer.domain.Insurance.dftModel.OkHttpUtil;
import com.ktgj.customer.domain.Insurance.hlModel.HLInsurance;
import com.ktgj.customer.util.DateUtils;
import com.ktgj.customer.util.Security;
import com.ktgj.customer.util.SysUtils;
import com.ktgj.customer.util.Util;
import org.apache.commons.codec.digest.DigestUtils;
import org.dom4j.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

public class HanglianUtils {

    private static final Logger logger = LoggerFactory.getLogger(HanglianUtils.class);
    private static final ObjectMapper MAPPER = new ObjectMapper();


    //   13116160086   航联 500万 产品代码
    //  pek602c        航联保险 企业代码


    //线下
    //private static string URL = "http://39.96.35.19:8080/auip/abe/insureOrder?key={0}&Uid=JSshiji";
    //private static string refundUrl = "http://39.96.35.19:8080/auip/abe/refundOrder?key={0}&Uid=JSshiji";

    //线上

    private String URL = "http://47.95.191.204:9001/auip/abe/insureOrder?key={0}&Uid=JSshiji";
    private String refundUrl = "http://47.95.191.204:9001/auip/abe/refundOrder?key={0}&Uid=JSshiji";

    //金色公钥纯字符串
    private String publicKeyPEM = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYNuQol+qYsj9qRahARIDODx5AAbqTP6PCKvP8tmUtlmyuk26ovpZTqQpLkkcaffFUZW1qdCd9Z+gq56lKo2KBgGEOjtDXrAeZIIjhb8tk2XwTY3SSV6QzZyrc0LW5OBzdkS6O9RmAcbzN80JhRkWRPgZSDLbkbcTIAnhbUYTO5wIDAQAB";
    //金色私钥
    private String privateKeyPEM = "-----BEGIN RSA PRIVATE KEY-----" +
            "MIICXQIBAAKBgQDYNuQol+qYsj9qRahARIDODx5AAbqTP6PCKvP8tmUtlmyuk26o" +
            "vpZTqQpLkkcaffFUZW1qdCd9Z+gq56lKo2KBgGEOjtDXrAeZIIjhb8tk2XwTY3SS" +
            "V6QzZyrc0LW5OBzdkS6O9RmAcbzN80JhRkWRPgZSDLbkbcTIAnhbUYTO5wIDAQAB" +
            "AoGARXq+Lt1CofcFsdzYiG57BbyN9/uWPSNCOG8dIKRsNw4TtrXh5Y/5NsEnccl7" +
            "1+OI3ZoKYx8YYZA2ZzMyj62ZRXUKW4wTwFqo9E8kI+XF2G9iYZNSLfEH+BDcsVtP" +
            "Xc6cXP0cwLjDQvFgkNRDQPBvoDhep0Tl4Fh4DrLYQDDSTuECQQDscu42QyAYm3KU" +
            "+7fYSK7FJDsxAWkZqh/b4SV9LUJOikSs03pnfPJdZxsWhoF42Pq1cB0pEAt/OBUT" +
            "QQwPdfZ9AkEA6hekqwbU6jLWK5BukIlMEQCm32efQnm/OMP51655Xj3Nui2xWAd7" +
            "Au8HW+HJGWo/AyFeteIzcHce15kaJhHEMwJBAIfeZwnhOqFJOedoWbU71snLzwOS" +
            "9uzbeGEmGB+9ERwGkf3pq62p+682XzdrZRynOjFmUitVX/XjqSCeQSrlMxUCQDbE" +
            "o1UUOxo0HKGCoCuWw8Iymdgo4TznSRLZ3wlUG7ct1IUbjaNf1KriC6G2mJsmnWl5" +
            "FDSPoKNOa1vbyR9hBrsCQQC2V6V/iVqIrCIVckFA8hZg0m7Z7RORR4H5AR1i7U65" +
            "fwekTy5PyQqW2shBw1ioddU5PmGozbiTkgu3Rgl8hnnH" +
            "-----END RSA PRIVATE KEY-----";
    //合作方公钥
    /*private String publicKeyPEM_hl = "-----BEGIN PUBLIC KEY-----" +
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4FGYGuMIypbE8RHoF9Z28J0FV" +
            "DgTcSNQJFlpHgSZwuvwg33ww9Q6tLut9beyiD2YESmk7kbtH971UeYePwlaGpa6l" +
            "bti59/uAnbJY45a26lPT9yCtroDWkLszJNn2kBUOI5js5UoArv25LsD83ODFIFtN" +
            "KOEsOb+624V8g9z9tQIDAQAB" +
            "-----END PUBLIC KEY-----";*/
    private String publicKeyPEM_hl = "" +
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4FGYGuMIypbE8RHoF9Z28J0FV" +
            "DgTcSNQJFlpHgSZwuvwg33ww9Q6tLut9beyiD2YESmk7kbtH971UeYePwlaGpa6l" +
            "bti59/uAnbJY45a26lPT9yCtroDWkLszJNn2kBUOI5js5UoArv25LsD83ODFIFtN" +
            "KOEsOb+624V8g9z9tQIDAQAB";


    public ApplyPolicyNoPayOutput _Create(String strRequest) {
        ApplyPolicyNoPayOutput output = new ApplyPolicyNoPayOutput();

        StringBuilder sblog = new StringBuilder();


        try {
            sblog.append("请求参数:" + strRequest);
            //加密
            strRequest = RSAUtils.publicEncrypt(strRequest, RSAUtils.getPublicKey(publicKeyPEM_hl));
            //获得key
            String key = DigestUtils.md5Hex(strRequest + publicKeyPEM);

            String posturl = URL.replaceAll("\\{0}", key);

            //发送post
            //string strRtn = CRM.Buzlogic.JsjWeb.Common._HTTP._PostUrlHtml(posturl, System.Text.Encoding.UTF8, strRequest, 1000 * 10, "application/xml;charset=UTF-8");
            String strRtn = HttpClientUtil.doPostXmlStream(posturl, strRequest);

            sblog.append("返回密文:" + strRtn);

            strRtn = RSAUtils.privateDecrypt(privateKeyPEM, RSAUtils.getPrivateKey(strRtn));
            sblog.append("密文解密:" + strRtn);
            PaInsuranceUtils.AuisInsuranceDataResponse response = (PaInsuranceUtils.AuisInsuranceDataResponse) convertXmlStrToObject(PaInsuranceUtils.AuisInsuranceDataResponse.class, strRtn);


            output.ret = response.ReturnCode;
            output.msg = response.ReturnMessage + "SerialNumber：" + response.SerialNumber;
            output.requestId = response.SerialNumber;
            if (response.PolicyInfo != null && !StringUtils.isEmpty(response.PolicyInfo.Code)) {
                Datum dd = new Datum();
                dd.applyPolicyNo = response.PolicyInfo.PolicyNo;
                dd.policyNo = response.PolicyInfo.PolicyNo;
                if (response.PolicyInfo.Code == "0") {
                    dd.resultCode = "200";
                }

                dd.resultMessage = response.PolicyInfo.Message;
                dd.totalActualPremium = "30";
                output.data = new ArrayList<>();
                output.data.add(dd);
            }


        } catch (Exception ex) {
            sblog.append("异常:" + ex.getMessage() + ex.getStackTrace());
            //SystemFileLog.WriteLog("航联保险开保异常", sblog.ToString());
        }
        return output;
    }

    /**
     * 航联保险接口
     * */
    public ApplyPolicyNoPayOutput _RequestXml(InsurancePassager passager, String SerialNumber, String strRequest) {
        ApplyPolicyNoPayOutput output;
//        StringBuilder sblog = new StringBuilder();

        Date dtBirth = null;
        Date dtn = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat time = new SimpleDateFormat("HH:mm");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = format.format(dtn);
        String strTime = dateFormat.format(dtn);

        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat formatTime = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        SimpleDateFormat dateFormatTime = new SimpleDateFormat("yyyy-MM-dd 23:59:59");

        Date date = null;
        try {
            date = simple.parse("2022-01-18 00:00:00");
        } catch (Exception e){
            System.out.println("date创建失败");
        }

        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        date = calendar.getTime();
        String InsuranceStartDate = formatTime.format(date);

        calendar.setTime(date);
        calendar.add(Calendar.YEAR, 1);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        date = calendar.getTime();
        String InsuranceEndDate = dateFormatTime.format(date);

        if (passager.getCardType() != Integer.parseInt("NI"))
        {
            dtBirth = passager.getBirthDay();
        }
        else
        {
            String dateTime = passager.getCardId().substring(6, 10)+"-"+passager.getCardId().substring(10, 12)+"-"+passager.getCardId().substring(12, 14);
            try {
                dtBirth = format.parse(dateTime);
            } catch (Exception e){
                System.out.println("获取生日失败");
            }
        }

        //团队开保
        //                BL：营业执照（三证合一之后只有营业执照一项了）
        //UC：统一社会信用代码
        //TR：税务登记证
        //OC：组织机构证


        //公司作为投保人
        String HolderName = "北京金色世纪商旅网络科技股份有限公司";
        String HolderIdType = "BL";
        String HolderId = "91110105582501947J";
        String HolderBirthday = "";
        String HolderPhone = "010-84926666";

        //个人作为投保人
        //string HolderName = passager.PassengerName;
        //string HolderIdType = _GetIdTypeForHl(passager.Cardtype);
        //string HolderId = passager.CardID;
        //string HolderBirthday = dtBirth.ToString("yyyy-MM-dd");
        //string HolderPhone = passager.ContactMobile;

        strRequest = String.format(strRequest,
                // 0-4
                passager.getOrderId(), strDate, strTime, "ALIPAY_CHARGE_JSSHIJI", passager.getOrderId(),
                // 5-9
                simpleDateFormat.format(dtn), "1.0", HolderName, HolderIdType, HolderId,
                //10-14
                HolderBirthday, HolderPhone, passager.getPassengerName(), _GetIdTypeForHl(passager.getCardType()), passager.getCardId(),
                //15-19
                format.format(dtBirth), passager.getContactMobile(), SerialNumber, UUID.fastUUID().toString().toUpperCase(), passager.getTicketNo().substring(0, 3),//passager.Insurance_Record_Id
                //20-24
                passager.getTicketNo(), passager.getTicketFare(), passager.getFlightNo().substring(0, 2), passager.getFlightNo(), passager.getDeparture(),
                //25-27
                passager.getArrival(), format.format(passager.getDepartureTime()), time.format(passager.getDepartureTime()), InsuranceStartDate, InsuranceEndDate
        );
        output = _Create(strRequest);
        return output;
    }

    private static String _GetIdTypeForHl(int nJsjIdType)
    {
        String strOutIdType = "";
        // 无证件 = 0, 身份证 = 1, 军人证 = 2, 学生证 = 3, 护照 = 4, 港澳居民来往内地通行证 = 5, 其他证 = 6,
        //台湾居民来往大陆通行证 = 7, 驾驶证 = 8, 港澳通行证 = 9, 户口本 = 10, 出生证明 = 11, 台湾通行证 = 12, 永久居留身份证 = 13, 港澳台居民居住证 = 14, 其他证件 = 99

        //保险公司枚举：NI	身份证
        //PP	护照
        //MD	军官证
        //HR	回乡证
        //TW	台胞证
        //HM	港澳通行证
        //RA	户口簿
        //BC	出生证明
        //OT	其他

        switch (nJsjIdType)
        {
            case 1:
            case 0:
                strOutIdType = "NI";//身份证
                break;
            case 2:
                strOutIdType = "MD";//军官证
                break;
            case 4:
                strOutIdType = "PP";//护照
                break;
            case 9:
                strOutIdType = "HM";//港澳通行证
                break;
            case 5:
                strOutIdType = "HR";//港澳居民来往内地通行证
                break;
            case 7:
                strOutIdType = "TW";//台湾居民来往大陆通行证
                break;
            case 11:
                strOutIdType = "BC";//出生证明
                break;
            case 10:
                strOutIdType = "RA";//出生证明
                break;
            case 6:
                strOutIdType = "OT";//其他
                break;
        }
        return strOutIdType;
    }


    @SuppressWarnings("unchecked")
    /**
     * 将String类型的xml转换成对象
     */
    public Object convertXmlStrToObject(Class clazz, String xmlStr) {
        Object xmlObject = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            // 进行将Xml转成对象的核心接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(xmlStr);
            xmlObject = unmarshaller.unmarshal(sr);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return xmlObject;
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="orderId">机票订单号</param>
    /// <param name="SerialNumber">开保时传的SerialNumber</param>
    public PaInsuranceUtils.AuisInsuranceDataResponse _Refund(String orderId, String serialNumber) {
        StringBuilder sblog = new StringBuilder();
        PaInsuranceUtils.AuisInsuranceDataResponse response = new PaInsuranceUtils.AuisInsuranceDataResponse();
        try {
            Date dt = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat dateFormatTime = new SimpleDateFormat("HH:mm");
            String strRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                    "<AuisInsuranceData>" +
                    "<Header>" +
                    "<DataSourceCode>AUIS_ABE</DataSourceCode>" +
                    "<TransferType>RFND</TransferType>" +
                    "<FomerOrderId>" + orderId + "</FomerOrderId>" +
                    "<Operator>JSshiji</Operator>" +
                    "<OperationDate>" + dateFormat.format(dt) + "</OperationDate>" +
                    "<OperationTime>" + dateFormatTime.format(dt) + "</OperationTime>" +
                    "</Header>" +
                    "<InsuranceInfo>" +
                    "<InsuranceList>" +
                    "<Insurance>" +
                    "<SerialNumber>" + serialNumber + "</SerialNumber>" +
                    "<OperateSerialNumber>" + UUID.randomUUID() + "</OperateSerialNumber>" +
                    "<InsuranceItem>" +
                    "<AuisAbe>" +
                    "<ReissueFlag>0</ReissueFlag>" +
                    "</AuisAbe>" +
                    "</InsuranceItem>" +
                    "</Insurance>" +
                    "</InsuranceList>" +
                    "</InsuranceInfo>" +
                    "</AuisInsuranceData>";
            //加密
            sblog.append("请求参数:" + strRequest);
            strRequest = RSAUtils.publicEncrypt(strRequest, RSAUtils.getPublicKey(publicKeyPEM_hl));
            //获得key
            String key = DigestUtils.md5Hex(strRequest + publicKeyPEM);

            String posturl = URL.replaceAll("\\{0}", key);

            //发送post
            String strRtn = HttpClientUtil.doPostXmlStream(posturl, strRequest);
            sblog.append("返回密文:" + strRtn);

            strRtn = RSAUtils.privateDecrypt(privateKeyPEM, RSAUtils.getPrivateKey(strRtn));
            sblog.append("密文解密:" + strRtn);
            response = (PaInsuranceUtils.AuisInsuranceDataResponse) convertXmlStrToObject(PaInsuranceUtils.AuisInsuranceDataResponse.class, strRtn);


        } catch (Exception ex) {
            sblog.append("异常:" + ex.getMessage() + ex.getStackTrace());
        } finally {
            //SystemFileLog.WriteLog("航联保险退保日志", sblog.ToString());
        }
        return response;
    }


//    {
//        "DataSourceCode":"AUIS_ABE",
//            "TransferType":"TKTS",
//            "FomerOrderId":"2021072000010716",
//            "Operator":"hrb888b",
//            "OperationDate":"2020-07-27",
//            "OperationTime":"07:43:30",
//            "bankReconciliation":{
//        "PaymentCode":"YEEPAY_FENZHAN",
//                "PaymentSerialNumber":"q1  ",
//                "PaymentAmount":"5",
//                "PaymentTime":"2020-07-27 07:43:30"
//    },
//        "insuranceInfo":{
//        "policyHolder":{
//            "HolderName":"黄晓明",
//                    "HolderIdType":"OT",
//                    "HolderId":"4545uuhd",
//                    "HolderPhone":"17611073857"
//        },
//        "policyInsured":{
//            "InsuredName":"黄晓明",
//                    "InsuredIdType":"OT",
//                    "InsuredId":"4545uuhd",
//                    "InsuredPhone":"17611073857"
//        },
//        "policyBeneficiary":{
//            "BeneficiaryType":"4"
//        },
//        "insuranceLists":[
//        {
//            "insurance":{
//            "SerialNumber":" q2 ",
//                    "OperateSerialNumber":"q3",
//                    "Product":{
//                "ProductCode":"12135160016",
//                        "InsuranceStartDate":" q4  ",
//                        "InsuranceEndDate":"q5 "
//            }
//        },
//            "InsuranceItem":{
//            "auisAbe":{
//                "AgentNo":"aui110c",
//                        "TicketPrice":"1000",
//                        "ReissueFlag":"0",
//                        "AirlineNo":"867",
//                        "EticketNo":"8672340037981",
//                        "BaggageNo":"5",
//                        "TicketType":"ALR-D",
//                        "Carrier":"LT",
//                        "FlightNo":"LT4329",
//                        "DepartureAirportCode":"HRB",
//                        "ArriveAirportCode":"ZUH",
//                        "FlightDate":"2021-08-22",
//                        "FlightTime":"08:45"
//            }
//        }
//        }
//        ]
//    },
//        "InvoiceDelivery":{
//        "IsDelivery":"1",
//                "RecipientName":"宛兵",
//                "RecipientPhone":"18515398000",
//                "DeliveryAddress":"0",
//                "DeliveryZipCode":"北京市东城区东直门南大街5号"
//    }
//    }

    /**
     * 航联保险开保接口
     * @param insurance
     * @return
     */
//    public String openInsurance(HLInsurance insurance)
//    {
//        return HangLianPost("auis.api.asi.insure", JSON.toJSONString(insurance));
//    }
//
//    private String HangLianPost(String tag, String input) {
//        //线下地址
////        String url = "https://open.ehanglian.com/api/service";
//
//        //线上地址
//        String url = "http://open.audt.com.cn:8013/api/service";
//        String companyId = "jsj";
//        String token = "6db36947fb6d44669fe0fdaa485f3efd";
//        String nonce = SysUtils.getUuid().replaceAll("-", "");
//        String timestamp = DateUtils.removeMidline(DateUtils.getNowDateTime());
//
//        String requestId = SysUtils.getUuid().replaceAll("-", "");
//        LocalDateTime localDateTime = LocalDateTime.now();
//        String sign = "";
//        sign = Security.sign(companyId, nonce, timestamp, token);
//        String postMsg = MessageFormat.format("<Auis>\n" +
//                "\t<RequestType>{0}</RequestType>\n" +
//                "\t<RequestId>{1}</RequestId>\n" +
//                "\t<RequestTime>{2}</RequestTime>\n" +
//                "\t<CompanyId>{3}</CompanyId>\n" +
//                "\t<RequestData>\n" +
//                "\t\t<![CDATA[ {4} ]]>\n" +
//                "\t</RequestData>\n" +
//                "</Auis>\n", tag, requestId, Util.localDateTimeToString(localDateTime, ""), companyId, input);
//        url = url + "?companyId=" + companyId + "&signature=" + sign + "&timestamp=" + timestamp + "&nonce=" + nonce;
//
//        String rst = OkHttpUtil.postXmlParams(url, postMsg);
//        logger.info("请求参数" + postMsg + "返回参数" + rst);
//
//        Document doc = null;
//        try {
//            doc = DocumentHelper.parseText(rst);
//        } catch (DocumentException e) {
//            logger.error("DocumentHelper转换失败", e);
//        }
//
//        String resultCode = doc.getRootElement().element("ResultCode").getText();
//        String resultMsg = doc.getRootElement().element("ResultMsg").getText();
//        if (!resultCode.equals("000000")) {
//            logger.error(resultMsg);
//            return "";
//        }
//        String responseData = doc.getRootElement().element("ResponseData").getText();
//
//        return responseData;
//    }

    public Auis openInsurance(HLInsurance insurance) throws Exception {
        Auis auis = HangLianPost("auis.api.asi.insure", JSON.toJSONString(insurance));
//        if (auis != null && !auis.equals("")){
            return auis;
//        }
//        else {
//            return null;
//        }
    }

    @JsonIgnoreProperties(ignoreUnknown =  true )
    private Auis HangLianPost(String tag, String input) throws Exception {
        //线下地址
//        String url = "https://open.ehanglian.com/api/service";

        /**
         * test_user：4eb9f65fa4164589983f2c09bac7d625
         * */

        //线上地址
        String url = "http://open.audt.com.cn:8013/api/service";
//        String companyId = "test_user";//jsj
        String companyId = "jsj";//
//        String token = "4eb9f65fa4164589983f2c09bac7d625";//6db36947fb6d44669fe0fdaa485f3efd
        String token = "6db36947fb6d44669fe0fdaa485f3efd";//
        String nonce = SysUtils.getUuid().replaceAll("-", "");
        String timestamp = DateUtils.removeMidline(DateUtils.getNowDateTime());

        String requestId = SysUtils.getUuid().replaceAll("-", "");
        LocalDateTime localDateTime = LocalDateTime.now();
        String sign = "";
        sign = Security.sign(companyId, nonce, timestamp, token);
        String postMsg = MessageFormat.format("<Auis>\n" +
                "\t<RequestType>{0}</RequestType>\n" +
                "\t<RequestId>{1}</RequestId>\n" +
                "\t<RequestTime>{2}</RequestTime>\n" +
                "\t<CompanyId>{3}</CompanyId>\n" +
                "\t<RequestData>\n" +
                "\t\t<![CDATA[ {4} ]]>\n" +
                "\t</RequestData>\n" +
                "</Auis>\n", tag, requestId, Util.localDateTimeToString(localDateTime, ""), companyId, input);
        url = url + "?companyId=" + companyId + "&signature=" + sign + "&timestamp=" + timestamp + "&nonce=" + nonce;

        String rst = OkHttpUtil.postXmlParams(url, postMsg);

        int countForward = rst.indexOf("<ResponseData>");
        int countBack = rst.indexOf("</ResponseData>");
        String xml = rst.substring(0, countForward + 14);
        xml = xml + rst.substring(countBack);

        String json = rst.substring(countForward + 14, countBack);
        json = json.substring(9);
        json = json.substring(0, json.length() - 3);

        XElement root = XElement.loadXml(xml);
        XmlMapper xmlMapper = new XmlMapper();
        String processedSystemIndex = xmlMapper.readValue(root.element("ProcessedSystemIndex").toString(), String.class);
        String requestType = xmlMapper.readValue(root.element("RequestType").toString(), String.class);
        String RequestId = xmlMapper.readValue(root.element("RequestId").toString(), String.class);
        String responseTime = xmlMapper.readValue(root.element("ResponseTime").toString(), String.class);
        String CompanyId = xmlMapper.readValue(root.element("CompanyId").toString(), String.class);
        String ResultCode = xmlMapper.readValue(root.element("ResultCode").toString(), String.class);
        String ResultMsg = xmlMapper.readValue(root.element("ResultMsg").toString(), String.class);
//        String responseData = xmlMapper.readValue(root.element("ResponseData").toString(), String.class);

        AuisVo auisVo = null;
        if (json != null && !json.equals("null")){
            String[] split = json.split("\\{");

            String tmpPolicyInfo = "{" + split[split.length - 1].substring(0, split[split.length - 1].length() - 2) + "}";

            String tmpAuisVo = "{" + split[split.length - 2] + "\"\"}";

            auisVo = JSONObject.parseObject(tmpAuisVo, AuisVo.class);
            PolicyInfo policyInfo = JSONObject.parseObject(tmpPolicyInfo, PolicyInfo.class);
            policyInfo.setEPolicyUrl(policyInfo.getEPolicyUrl().substring(9, policyInfo.getEPolicyUrl().length() - 3));
            auisVo.setPolicyInfo(policyInfo);
        }

        Auis auis = new Auis();
        auis.setRequestId(RequestId);
        auis.setCompanyId(CompanyId);
        auis.setResponseData(auisVo);
        auis.setResultMsg(ResultMsg);
        auis.setResponseTime(responseTime);
        auis.setProcessedSystemIndex(processedSystemIndex);
        auis.setResultCode(ResultCode);
        auis.setRequestType(requestType);

        logger.info("请求参数" + postMsg + "返回参数" + rst);

        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml);
        } catch (DocumentException e) {
            logger.error("DocumentHelper转换失败", e);
        }

        String resultCode = doc.getRootElement().element("ResultCode").getText();
        String resultMsg = doc.getRootElement().element("ResultMsg").getText();
        if (!resultCode.equals("000000")) {
            logger.error(resultMsg);
//            return null;
        }
//        String responseData = doc.getRootElement().element("ResponseData").getText();

        return auis;
    }
}

